package se.kth.id2212.market;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.*;
import se.kth.id2212.bankjdbc.Account;
import se.kth.id2212.bankjdbc.Bank;
import se.kth.id2212.bankjdbc.BankImpl;
import se.kth.id2212.bankjdbc.RejectedException;

@SuppressWarnings("serial")
public class TraderImpl extends UnicastRemoteObject implements Trader {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    //private static final int DATABASE_VERSION = 1;
    private String name;
    private float balance;
    private Bank bankobj;
    private PreparedStatement getBalanceStatement;
    private PreparedStatement createItemStatement;
    private PreparedStatement findItemStatement;
    private PreparedStatement deleteItemStatement;

    public TraderImpl(String name, Bank bankobj, Connection connection) throws RemoteException, RejectedException {
        // TODO Auto-generated constructor stub		
        super();
        this.name = name;
        this.bankobj = bankobj;

    }

    private void prepareStatement(Connection connection) throws SQLException {
        createItemStatement = connection.prepareStatement("INSERT INTO " + MarketImpl.TABLE_NAME2 + " VALUES (?, 0, ?)");
        findItemStatement = connection.prepareStatement("SELECT * FROM " + MarketImpl.TABLE_NAME2 + " WHERE NAME = ?");
        deleteItemStatement = connection.prepareStatement("DELETE FROM " + MarketImpl.TABLE_NAME2 + " WHERE NAME = ?");
        getBalanceStatement = connection.prepareCall("SELECT * FROM " + BankImpl.TABLE_NAME + " WHERE name = ?");
    }

    public synchronized void sellItem(String item, float price) throws RemoteException {
        try {
            createItemStatement.setString(1, item);
            createItemStatement.setFloat(2, price);
            createItemStatement.setString(3, name);
            createItemStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public synchronized boolean buyItem(String item) throws RemoteException, RejectedException {
        ResultSet result;
        boolean confirmed = false;
        float price;
        String trader;
        Account acct;
        try {
            result = getBalanceStatement.executeQuery();
            balance = result.getFloat(BankImpl.BALANCE);
            findItemStatement.setString(1, item);
            result = findItemStatement.executeQuery();
            price = result.getFloat(MarketImpl.PRICE);
            trader = result.getString(MarketImpl.TRADER);
            if (balance >= price) {
                acct = bankobj.getAccount(name);
                acct.withdraw(price);

                deleteItemStatement.setString(1, item);
                int re = deleteItemStatement.executeUpdate();

                if (re == 1) {
                    confirmed = true;
                } else {
                    throw new RejectedException("Error occured when placing your order.");
                }

                acct = bankobj.getAccount(trader);
                acct.deposit(price);

            } else {
                throw new RejectedException("Your balance is not enough.");
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return confirmed;
    }
}
